﻿var zombies = zombies || {};

zombies.mailManager = function () {
    var self = this;
    self.Subject = ko.observable();
    self.Body = ko.observable();
    self.Sending = ko.observable(false);

    self.Types = ko.observableArray([
        { name: 'Email thông báo đăng ký thành công', id: 1 },
        { name: 'Email thông báo đơn hàng', id: 2 },
        { name: 'Email thông báo đã giao hàng', id: 3 }
    ]);
    self.SelectedType = ko.observable();

    self.doChange = function () {
        loadMailTemplate(self.SelectedType());
    };

    self.doUpdate = function () {
        var dataToSave = {
            Type: self.SelectedType(),
            Subject: self.Subject(),
            Body: CKEDITOR.instances['mail_body'].getData()
        };
        $.ajax({
            url: '/api/EmailManager/PostEmailFormat',
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            data: ko.toJSON(dataToSave)
        }).done(function (data) {
            toastr.success('Sửa format email thành công');
        }).error(function () {
            toastr.error('Lưu lỗi');
        })
    };

    self.doBroadcast = function () {
        self.Sending(true);
        var dataToSave = {
            Subject: self.Subject(),
            Body: CKEDITOR.instances['mail_body'].getData()
        };
        $.ajax({
            url: '/api/EmailManager/BroadcastEmail',
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            data: ko.toJSON(dataToSave)
        }).done(function (data) {
            toastr.success(data);
            self.Sending(false);
        }).error(function () {
            toastr.error('Lưu lỗi');
        })
    };

};

var loadMailTemplate = function (id) {
    $.ajax({
        url: '/api/EmailManager/getEmailTemplate/' + id,
        type: "GET",
        contentType: "application/json",
        dataType: "json"
    }).done(function (item) {
        viewModel.Body(item.Body);
        viewModel.Subject(item.Subject);
        CKEDITOR.instances['mail_body'].setData(item.Body);
    }).error(function () {
        toastr.error('load lỗi');
    })
};



var viewModel;
$(document).ready(function () {

    viewModel = new zombies.mailManager();

    ko.applyBindings(viewModel, document.getElementById("admin_content"));

});